window.onload = function () {

    //基础数据
    const simpleData = [
        { src: '.\/images\/pineapple.svg', dataId: "1" },
        { src: '.\/images\/apple.svg', dataId: "2" },
        { src: '.\/images\/avocado.svg', dataId: "3" },
        { src: '.\/images\/grapes.svg', dataId: "4" },

    ]
    //卡片大小
    const size = 70
    // 行
    const rows = 6
    // 列
    const cols = 6
    // 3个一消除
    const oneGroupCount = 3
    // 每个消除有4组
    const group = 4
    // 总共4层
    const layerCount = 5
    const cellHtml = []
    const renderData = Array.from(new Array(oneGroupCount * group)).map(v => {
        return simpleData.map(v => ({ ...v }))
    }).flat().sort(v => Math.random() - 0.5)
    //渲染出页面
    for (let ly = layerCount - 1; ly >= 0; ly--) {
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                let pyStep = (ly + 1) % 2 === 0 ? size / 2 : 0
                let item = (Math.random() > 0.7 ? renderData.pop() : false)
                if (item) {
                    cellHtml.push(`<div class='item' id="m${ly}-${i}-${j}" data-id="${item.dataId}"
                style="width:${size}px; height:${size}px; left:${size * j + pyStep}px; top:${size * i + pyStep}px;
                "><img src='${item.src}'></div>`)
                }
            }
        }

    }
    const main = document.querySelector('.main')
    main.innerHTML = cellHtml.reverse().join('')
    main.style.height = `${size * rows + size * 2}px`
    main.style.width = `${size * cols}px`


    //计算出被遮住的底牌，并且标注暗色
    const checkDisabled = () => {
        main.querySelectorAll('.item').forEach((v, i) => {
            const arr = v.id.substring(1).split('-').map(v => Number(v))
            //isPy偶数层
            const isPy = (arr[0] + 1) % 2 === 0
            for (let i = arr[0] + 1; i <= layerCount - 1; i++) {
                const isPyB = (i + 1) % 2 === 0
                // 当前层和对比层在不同层，相同坐标
                if (isPy === isPyB) {
                    const el = main.querySelector(`#m${i}-${arr[1]}-${arr[2]}`)
                    if (el) {
                        v.classList.add('disabled')
                        break;
                    }

                }
                // 当前层在偶数层，对比层在奇数层
                else if (isPy && !isPyB) {
                    const result = [
                        `${i}-${arr[1]}-${arr[2]}`,
                        `${i}-${arr[1]}-${arr[2] + 1}`,
                        `${i}-${arr[1] + 1}-${arr[2]}`,
                        `${i}-${arr[1] + 1}-${arr[2] + 1}`
                    ].every(k => {
                        return !main.querySelector('#m' + k)
                    })
                    if (!result) {
                        v.classList.add('disabled')
                        break;
                    } else {
                        v.classList.remove('disabled')

                    }
                }
                // 当前层在奇数层，对比层在偶数层
                else if (!isPy && isPyB) {
                    const result = [
                        `${i}-${arr[1]}-${arr[2]}`,
                        `${i}-${arr[1]}-${arr[2] - 1}`,
                        `${i}-${arr[1] - 1}-${arr[2]}`,
                        `${i}-${arr[1] - 1}-${arr[2] - 1}`
                    ].every(k => {
                        return !main.querySelector('#m' + k)
                    })
                    if (!result) {
                        v.classList.add('disabled')
                        break;
                    } else {
                        v.classList.remove('disabled')

                    }
                }

            }
            if (v.classList.contains('disabled') == true) {
                v.classList.add('notclick')
            } else {
                v.classList.remove('notclick')
            }
        })
    }
    checkDisabled()
    //记录数据
    var count = [{ 1: 0 }, { 2: 0 }, { 3: 0 }, { 4: 0 }]
    var frults = 0
    //记录消去图片个数
    reNums = 0

    var items = main.querySelectorAll('.item')
    var box = document.querySelector('#box')
    let left = box.offsetLeft
    let top = box.offsetTop
    for (let i = 0; i < items.length; i++) {

        items[i].onclick = function (e) {
            e.preventDefault()
            Music()
            // console.log(this);
            // this.style.dispaly = 'none'
            if (isMax()) {
                var item = this.cloneNode(true)
                if (box.childNodes.length > 0) {
                    var el = box.lastElementChild
                    left = el.offsetLeft + size
                }
                item.style.left = `${left + 20}px`
                item.style.top = `${top}px`
                main.removeChild(this)
                box.appendChild(item)
                Count(node = this)
                isRemove()
                if (!isMax()) {
                    if (confirm('您已经输了哦！笨蛋,是否要重开一局一雪前耻呢？')) {
                        location.reload()
                    } else {
                        window.close()
                    }

                }

            } else {
                if (confirm('您已经输了哦！笨蛋,是否要重开一局一雪前耻呢？')) {
                    location.reload()
                } else {
                    window.close()
                }

            }
            checkDisabled()
            isVerty()
        }
    }

    //判断是否达到最大值
    const isMax = function () {
        let len = box.childNodes.length < 7 ? true : false
        return len
    }
    //计数
    const Count = function (node) {
        let num = parseInt(node.getAttribute('data-id'))
        count[num - 1][num] += 1
        // console.log(count);
    }
    //判断是否移除
    const isRemove = function () {
        var boxs = box.querySelectorAll('.item')
        for (let i = 0; i < count.length; i++) {

            if (count[i][i + 1] === 3) {
                var frults = i + 1
                count[i][i + 1] -= 3
            }
        }
        for (let j = 0; j < boxs.length; j++) {
            if (frults != 0 && parseInt(boxs[j].getAttribute('data-id')) == frults) {
                box.removeChild(boxs[j])

            }
        }
        boxs = box.querySelectorAll('.item')
        boxs.forEach((v, i) => {
            v.style.left = `${i * size}px`
        })
    }
    //判断是否胜利
    const isVerty = function () {
        items = main.querySelectorAll('.item')
        // console.log(reNums);
        if (items.length == 0) {
            alert('恭喜你，赢了哦');
            location.reload()

        }
    }
    const Music = function () {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        (function () {
            if (!window.AudioContext) {
                alert('当前浏览器不支持Web Audio API');
                return;
            }

            // 创建新的音频上下文接口
            var audioCtx = new AudioContext();

            // 发出的声音频率数据，表现为音调的高低
            var arrFrequency = [196.00, 220.00, 246.94, 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25, 587.33, 659.25, 698.46, 783.99, 880.00, 987.77, 1046.50];

            // 音调依次递增或者递减处理需要的参数
            var start = 0, direction = 1;


            // 当前频率
            var frequency = arrFrequency[start];
            // 如果到头，改变音调的变化规则（增减切换）
            if (!frequency) {
                direction = -1 * direction;
                start = start + 2 * direction;
                frequency = arrFrequency[start];
            }
            // 改变索引，下一次hover时候使用
            start = start + direction;

            // 创建一个OscillatorNode, 它表示一个周期性波形（振荡），基本上来说创造了一个音调
            var oscillator = audioCtx.createOscillator();
            // 创建一个GainNode,它可以控制音频的总音量
            var gainNode = audioCtx.createGain();
            // 把音量，音调和终节点进行关联
            oscillator.connect(gainNode);
            // audioCtx.destination返回AudioDestinationNode对象，表示当前audio context中所有节点的最终节点，一般表示音频渲染设备
            gainNode.connect(audioCtx.destination);
            // 指定音调的类型，其他还有square|triangle|sawtooth
            oscillator.type = 'triangle';
            // 设置当前播放声音的频率，也就是最终播放声音的调调
            oscillator.frequency.value = frequency;
            // 当前时间设置音量为0
            gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
            // 0.01秒后音量为1
            gainNode.gain.linearRampToValueAtTime(1, audioCtx.currentTime + 0.01);
            // 音调从当前时间开始播放
            oscillator.start(audioCtx.currentTime);
            // 1秒内声音慢慢降低，是个不错的停止声音的方法
            gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1);
            // 1秒后完全停止声音
            oscillator.stop(audioCtx.currentTime + 1);

        })();
    }
}

